/**
 * @param {number[]} nums
 * @param {number} m
 * @return {number}
 */
var splitArray = function(nums, m) {
    let low = 0;
    let high = 0;
    for(const n of nums) {
        low = Math.max(low, n);
        high += n;
    }

    while(high > low) {
        if (high - low < 4) {
            for(let i = low; i <= high; i++) {
                if (trySplit(nums, i, m)) {
                    return i;
                }
            }
        } else {
            const mid = Math.floor((high + low) / 2);
            if (trySplit(nums, mid, m)) {
                high = mid;
            } else {
                low = mid;
            }
        }
    }
    return high;
};

function trySplit(nums, top, m) {
    let sum = 0;
    let seg = 1;
    for(let i = 0; i < nums.length; i++) {
        const n = nums[i];
        if (sum + n <= top) {
            sum += n;
        } else {
            sum = n;
            seg += 1;
        }
        if (seg > m) return false; // 不可分，上限太小
    }
    return true; // 可分
}


console.log(splitArray([7,2,5,10,8], 2))